package com.b2c.repository.erp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.ExpressEntity;
import com.b2c.entity.ErpOrderEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.erp.EnumErpOrderlogisticsPrintStatus;
import com.b2c.repository.Tables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:物流相关 pbd add 2019/6/17 9:12
 */
@Repository
public class ExpressRepository {
    private static Logger log = LoggerFactory.getLogger(ExpressRepository.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 打印快递单
     *
     * @param orderId
     * @param kuaidicom
     * @param kuaidinum
     * @param imgBase64
     * @return
     */
    @Transactional
    public ResultVo<Integer> printExpress(Long orderId, String kuaidicomName, String kuaidicom, String kuaidinum, String imgBase64) {
        ErpOrderEntity order = new ErpOrderEntity();
        try {
            //查询订单
            order = jdbcTemplate.queryForObject("select * from " + Tables.ErpOrder + " WHERE id=? ", new BeanPropertyRowMapper<>(ErpOrderEntity.class), orderId);
        } catch (Exception e) {
            return new ResultVo<>(EnumResultVo.NotFound, "没找到订单");
        }

        /********插入order_send_express*********/

        String addSendExpress = "INSERT INTO order_send_express set order_num=?,send_company_code=?,send_code=?,send_print_img=?,create_on=unix_timestamp(now())";
        jdbcTemplate.update(addSendExpress, order.getOrder_num(), kuaidicom, kuaidinum, imgBase64);

        /********更新出货信息，状态*********/
        String updErpOrderSQL = "UPDATE " + Tables.ErpOrder + " SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,modifyTime=?,logisticsPrintStatus=?,logisticsPrintCount=logisticsPrintCount+1,logisticsPrintTime=?,logisticsPrintType=2 WHERE id=? ";
        jdbcTemplate.update(updErpOrderSQL, kuaidicomName, kuaidicom, kuaidinum, System.currentTimeMillis() / 1000,
                EnumErpOrderlogisticsPrintStatus.Printed.getIndex(), System.currentTimeMillis() / 1000,
                orderId);

        return new ResultVo<>(EnumResultVo.SUCCESS);
    }

    /**
     * 云打印生成图片
     *
     * @param print
     */
//    public String printImg(PrintImgVo print) {
//        try {
//            List<UserAddressEntity> list = addressRepository.getAddressByUserId(0);
//            if (null == list || list.size() <= 0) return null;
//            //网站首页
//            SysVariableEntity variable = systemRepository.getVariable(VariableEnums.URL_WMS_INDEX.name());
//            //寄件人地址
//            UserAddressEntity address = list.get(0);
//            Map<String, String> params = new HashMap<>();
//            //params.put("method", "getPrintImg");
//            params.put("key", "HemHbdOY1667");
//            String now = String.valueOf(System.currentTimeMillis());
//            params.put("t", now);
//
//            JSONObject param = new JSONObject();
//            param.put("type", "10");
//            param.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
//            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");
//
//            //收件人
//            param.put("recManName", print.getRecManName());
//            param.put("recManMobile", print.getRecManMobile());
///*            param.put("recManProvince",print.getRecManProvince());
//            param.put("recManCity",print.getRecManCity());
//            param.put("recManDistrict",print.getRecManDistrict());
//            param.put("recManAddr",print.getRecManAddr());*/
//            param.put("recManPrintAddr", print.getRecManPrintAddr());
//
//            //发件人
//            param.put("sendManName", address.getConsignee());
//            param.put("sendManMobile", address.getMobile());
//            param.put("sendManProvince", address.getProvinceName());
//            param.put("sendManCity", address.getCityName());
//            param.put("sendManDistrict", address.getDistrictName());
//            param.put("sendManAddr", address.getAddress());
//            param.put("sendManPrintAddr", address.getProvinceName() + address.getCityName() + address.getAddress());
//
//            //快递信息
//            param.put("orderId", print.getOrderId());//订单编号
//            param.put("cargo", print.getCargo());
//            param.put("count", print.getCount());
//            param.put("weight", print.getWeight());
//            param.put("volumn", print.getVolumn());
//            param.put("tempid", "5ada972099e8483faef7b33113a0dc6f");//面单id
//            param.put("kuaidicom", print.getKuaidicom());//快递公司
//            param.put("net", print.getNet());
//            param.put("needChild", "0");
//            param.put("needBack", "0");
//            param.put("op", "1");//是否开启订阅功能，默认是：0（不开启），如果是1说明开启订阅功能此时pollCallBackUrl必须填入
//            param.put("pollCallBackUrl", variable.getValue() + "/notify/express_notify");
//            param.put("resultv2", "0");
//
//
//            StringBuilder builder = new StringBuilder(param.toJSONString());
//            builder.append(now);
//            builder.append("HemHbdOY1667");
//            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
//            params.put("sign", Md5Util.MD5(builder.toString()));
//
//            StringBuilder builder_1 = new StringBuilder("&param=" + param.toJSONString());
//            builder_1.append("&" + HttpUtil.map2Url(params));
//
//            HttpResponse<String> response = ExpressClient.doPost("http://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg", builder_1.toString());
//            //{"result":true,"returnCode":"200","message":"提交成功","data":{"taskId":"****",//任务ID"kuaidicom":"****",//快递公司编码"kuaidinum":"****",//快递单号"imgBase64":"****"//面单BASE64编码图片}}
//            if (response.statusCode() == 200) {
//                //log.info("请求打印快递单返回信息："+response.body());
//                JSONObject obj = JSONObject.parseObject(response.body());
//                if (obj.getInteger("returnCode") == 200) {
//                    //添加快递打印图片
//                    String str = obj.getString("data").replace("[\\\"", "");
//                    String str_1 = str.replace("\\\"]", "");
//                    String str_2 = str_1.replace("\\\\n", "");
//                    JSONObject dataObj = JSONObject.parseObject(str_2);
//                    String addSendExpress = "INSERT INTO order_send_express set order_num=?,send_company_code=?,send_code=?,send_print_img=?,create_on=unix_timestamp(now())";
//                    jdbcTemplate.update(addSendExpress, print.getOrderId(), dataObj.getString("kuaidicom"), dataObj.getString("kuaidinum"), dataObj.getString("imgBase64"));
//                    //更新出货信息
//                    String updErpInvoice = "UPDATE " + Tables.Order + " SET send_company=?,send_company_code=?,send_code=?,send_time=unix_timestamp(now()),send_status=3 WHERE order_num=? ";
//                    jdbcTemplate.update(updErpInvoice, "韵达快递", dataObj.getString("kuaidicom"), dataObj.getString("kuaidinum"), print.getOrderId());
//                    return dataObj.getString("imgBase64");
//                }
//            }
//        } catch (Exception e) {
//            log.error("请求打印快递单异常：" + e);
//        }
//        return null;
//
//    }

    /**
     * 查询订单发货物流信息
     *
     * @param orderNum
     * @return
     */
    public ExpressEntity getExpress(String orderNum) {
        String sql = "SELECT * FROM order_send_express where order_num=? ";
        List<ExpressEntity> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ExpressEntity.class), orderNum);
        if (null != list && list.size() > 0) return list.get(0);
        return null;
    }

    /**
     * 更新快递信息平台
     *
     * @param obj
     */
    public void updExpressInfo(JSONObject obj) {
        JSONObject express = obj.getJSONObject("lastResult");//快递信息
        JSONArray expressInfo = express.getJSONArray("data");//快递最新物流信息
        StringBuilder builder = new StringBuilder();
        expressInfo.parallelStream().forEach(i -> {
            JSONObject expressData = JSONObject.parseObject(JSON.toJSONString(i));
            builder.append(expressData.getString("context"));
            builder.append("\\ln");
            builder.append(expressData.getString("ftime"));
            builder.append("\\ln");

        });
        jdbcTemplate.update("update order_logistics set comment=? where order_id=(select id from orders where send_code=?) ", builder.toString(), express.getString("nu"));


    }
}
